"""
这个是发起http请求的工具类
"""
import time

import requests

from core.decorates import http_retry


class HttpClient(object):
    user_agent = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
                  "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/125.0.0.0 Safari/537.36")

    def __init__(self):
        self._session = requests.Session()
        self.last_time = time.time()

    @http_retry(max_retries=3, retry_delay=1, offset=2)
    def __request(self, method, url, **kwargs):
        """
        请求数据的request方法
        :param method: 请求方式，如get，post
        :param url: 请求的url
        :param kwargs: key-value参数，包含所有request支持的key，同时加入了自定义参数
        random_ua，默认为True，启用随机ua，注意移动端和pc端会随机给
        use_proxy， 是否启用代理，默认False，不启用
        :return:
        """
        _ua = self.user_agent

        # 请求头处理
        default_headers = {"User-Agent": _ua}
        kwargs.update({"headers": {**default_headers, **kwargs.get("headers", {})}})

        resp = self._session.request(method, url, timeout=30, **kwargs)
        resp.raise_for_status()
        return resp

    def get(self, url, params=None, **kwargs):
        return self.__request("get", url, params=params, **kwargs)

    def post(self, url, data=None, json=None, **kwargs):
        return self.__request("post", url, data=data, json=json, **kwargs)

    def put(self, url, data=None, **kwargs):
        return self.__request("put", url, data=data, **kwargs)

    def delete(self, url, **kwargs):
        return self.__request("delete", url, **kwargs)
